package eu.liquify.ui {
	import flash.display.DisplayObject;
	import no.doomsday.console.ConsoleUtil;
	public class Grid extends UIContainer {
		private static const COLUMNS:int = 0;
		private static const ROWS:int = 1;
		
		public var gridHeight:Number;
		
		private var gridType:int = COLUMNS;
		public var size:int = 2;
		
		public var cellPadding:Number = 3;
		
		public function Grid() {}
		
		override public function addChild(child:DisplayObject):DisplayObject {
			super.addChild(child);
			reposition();
			return child;
		}
		
		public function set type(v:String):void {
			if (v == "col" || v == "column") gridType = COLUMNS;
			else if (v == "row") gridType = ROWS;
		}
		
		private function reposition():void {
			var i:int;
			var index:int;
			
			var d:DisplayObject;
			
			var w:Number = 0;
			var h:Number = 0;
			
			var cw:Number = 0;
			var ch:Number = 0;
			
			var rowHeights:Vector.<Number> = new Vector.<Number>(size);
			var rowPositions:Vector.<Number> = new Vector.<Number>(size);
			rowPositions[0] = cellPadding;
			for (i = 0; i < numChildren; i++) {
				d = getChildAt(i);
				index = i%size;
				if (d.height > rowHeights[index]) {
					rowHeights[index] = d.height;
					if (i < size-1) rowPositions[index+1] = d.height;
				}
			}
			for (i = 1; i < rowPositions.length; i++) {
				rowPositions[i] += rowPositions[i-1]+cellPadding;
			}
			
			var gridHeight:Number = 0;
			
			for (i = 0; i < numChildren; i++) {
				d = getChildAt(i);
				
				if (i%size == 0) {
					w += cw+cellPadding;
					cw = 0;
					//if (ch > h) h = ch;
					//ch = cellPadding;
				}
				
				d.x = w;
				//d.y = ch+maxHeights[i%size]/2-d.height/2;
				d.y = rowPositions[i%size]+rowHeights[i%size]/2-d.height/2;
				
				//ch += d.height+cellPadding;
				
				if (d.width > cw) cw = d.width;
				if (d.y+d.height > gridHeight) gridHeight = d.y+d.height;
			}
			
			w += cw+cellPadding;
			h = gridHeight+cellPadding;
			
			width = w;
			height = h;
		}
	}

}